import 'dart:convert';
import 'dart:math';

import 'package:flutter/foundation.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:ws_group_chat/model/chat_model.dart';

class ClientData extends ChangeNotifier {
  String userName = "Player${Random().nextInt(1000000)}";
  bool isHost = true;
  int playersCount = 1; // 默认1个玩家
  String? wsUrl;
  WebSocketChannel? _clientChannel;
  bool _isConnected = false;
  Function? onChatRoomStarted;
  bool isChatting = false;
  List<ChatModel> chatMessages = [];
  // 客户端模式：连接服务器
  Future<bool> connectToServer() async {
    try {
      _clientChannel = WebSocketChannel.connect(Uri.parse(wsUrl!));
      _clientChannel!.stream.listen(
        (message) => _handleComingMessage(message),
        onDone: () {
          _isConnected = false;
          notifyListeners();
        },
        onError: (error) {
          _isConnected = false;
          notifyListeners();
        },
      );
      await Future.delayed(const Duration(seconds: 1), () {
        sendJoinMessage();
      });
      _isConnected = true;
      notifyListeners();
      return true;
    } catch (e) {
      print(e);
      return false;
    }
  }

  // 发送加入消息
  void sendJoinMessage() {
    final joinMessage = {'type': 'join', 'player': userName};
    _clientChannel?.sink.add(jsonEncode(joinMessage));
  }

  void onDoneAndError(WebSocketChannel channel) {
    _isConnected = false;
    playersCount--;
    notifyListeners();
  }

  void _handleComingMessage(dynamic rawMsg) {
    try {
      final msg = jsonDecode(rawMsg);
      if (msg['type'] == 'hostData') {
        playersCount = msg['data']['playerCount'];
        notifyListeners();
        if (msg['data']['isChatting']) {
          if (!isChatting) {
            bool? result = onChatRoomStarted?.call();
            if (result == true) {
              isChatting = true;
            }
          }
        }
      } else if (msg['type'] == 'startChatRoom') {
        onChatRoomStarted?.call();
      } else if (msg['type'] == 'chat_msg') {
        final chatModel = ChatModel.fromJson(
          jsonDecode(msg['data']['chat_model']),
        );
        chatMessages.add(chatModel);
        notifyListeners();
      }
    } catch (e) {
      print(e);
      print(rawMsg);
    }
  }

  void sendMessage(String message) {
    final chatModel = ChatModel(userName: userName, msg: message);
    _clientChannel?.sink.add(
      jsonEncode({
        'type': 'chat_msg',
        'data': {'chat_model': chatModel.toJsonString()},
      }),
    );
  }

  void close() {
    print('clear');
    playersCount = 1;
    isChatting = false;
    onChatRoomStarted = null;
    _isConnected = false;
    _clientChannel?.sink.close();
    _clientChannel = null;
  }
}
